﻿using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Runtime.Caching;
using System.Threading.Tasks;
using System.Web;

namespace MakeWeekConcerts.Models
{
    public class YoutubeVideo
    {
        private static MemoryCache VideoCache = new MemoryCache("Videos");

        public YoutubeVideo()
        {
            this.Thumbnails = new List<YoutubeThumbnail>();
        }

        public string Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public List<YoutubeThumbnail> Thumbnails { get; set; }

        public string GetEmbed()
        {
            return string.Format("<iframe title=\"YouTube video player\" class=\"youtube-player\" type=\"text/html\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/{0}\" frameborder=\"0\" allowFullScreen></iframe>", this.Id);
        }

        public static async Task<List<YoutubeVideo>> GetVideosFor(string artistName)
        {
            if (VideoCache.Contains(artistName))
            {
                return (List<YoutubeVideo>)VideoCache.Get(artistName);
            }

            var service = new YouTubeService(new BaseClientService.Initializer() { ApplicationName = "Concert Finder", ApiKey = ConfigurationManager.AppSettings["Google:APIKey"] });
            var search = service.Search.List("snippet");
            search.Q = artistName + " music official";
            search.Order = SearchResource.ListRequest.OrderEnum.Relevance;

            var response = await search.ExecuteAsync();
            var results = new List<YoutubeVideo>();
            foreach (var video in response.Items.Where(x => x.Id.Kind == "youtube#video"))
            {
                var ytv = new YoutubeVideo() { Id = video.Id.VideoId };
                ytv.Title = video.Snippet.Title;
                ytv.Description = video.Snippet.Description;
                foreach (var thumbnail in new Thumbnail[] { video.Snippet.Thumbnails.Default, video.Snippet.Thumbnails.High, video.Snippet.Thumbnails.Maxres, video.Snippet.Thumbnails.Medium, video.Snippet.Thumbnails.Standard })
                {
                    if (thumbnail != null)
                    {
                        ytv.Thumbnails.Add(new YoutubeThumbnail() { Uri = thumbnail.Url, Height = thumbnail.Height, Width = thumbnail.Width, Type = "Standard" });
                    }
                }
                results.Add(ytv);
            }
            VideoCache.Add(artistName, results, new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromDays(1) });
            return results;
        }
    }

    public class YoutubeThumbnail
    {
        public string Type { get; set; }

        public string Uri { get; set; }

        public long? Height { get; set; }

        public long? Width { get; set; }

        public string GetHtml()
        {
            return string.Format("<img src=\"{0}\" {1} {2}/>", this.Uri,
                this.Height.HasValue ? string.Format("height=\"{0}\"", this.Height.Value) : "",
                this.Width.HasValue ? string.Format("width=\"{0}\"", this.Width.Value) : "");
        }
    }
}